﻿using System;
using System.Web;
using System.IO;
using eCommerce.core.Helpers;
using eCommerce.db.BORespository;
using eCommerce.db.DataRespository;

namespace WebApplication1.uploadify
{    
    public class Upload : IHttpHandler
    {
        private int _count;

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                HttpPostedFile file = context.Request.Files["filedata"];

                var lstId = context.Request.QueryString["uId"];

                var arrayId     = lstId.Split('-');
                var userId      = Utils.ToInt32(arrayId[0]);
                var productId   = Utils.ToInt32(arrayId[1]);

                if (userId > 0)
                {
                    _count++;

                    var dt = DateTime.Now;

                    var fileExtension   = Path.GetExtension(file.FileName.ToLower());
                    var folderPath      = productId > 0 
                                            ? string.Format("/Data/UserData/{0}/{1}/{2}/{3}/{4}/", userId, dt.Year, dt.Month, dt.Day, productId) 
                                            : string.Format("/Data/UserData/{0}/{1}/{2}/{3}/", userId, dt.Year, dt.Month, dt.Day);

                    var folder = context.Server.MapPath(folderPath);

                    if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

                    var strPath = folderPath + file.FileName.ToLower();
                    var strFile = context.Server.MapPath(strPath);

                    file.SaveAs(strFile);                                   

                    var fileSize = file.ContentLength / 1000;
                    context.Response.Write(string.Format("{0},{1},{2}", strFile, file.FileName, fileSize));
                    context.Response.StatusCode = 200;

                    if (productId > 0)
                    {
                        try
                        {
                            var o = new ImageEntity();
                            o.ProductId     = productId;
                            o.Priority      = _count;
                            o.ImagePath     = strPath;
                            ImageBo.Create(o);
                        }
                        catch { }
                    }                                     
                }                
            }
            catch (Exception ex)
            {
                context.Response.Write("Uploadify Error: " + ex.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}